package common

import (
	"errors"
	"fmt"
	"gin_scaffold/dao"
	"gin_scaffold/dto"
	"gin_scaffold/lib"
	"github.com/gin-gonic/gin"
	"github.com/golang-jwt/jwt/v5"
	"github.com/google/uuid"
	"io/ioutil"
	"net/http"
)

type DetailRes struct {
	Uid          string `json:"uid"`
	Token        string `json:"token"`
	RefreshToken string `json:"refresh_token"`
	Phone        string `json:"phone"`
}

func Logindetail(c *gin.Context, data dto.Wxlogin, from string, remoteIp string, platform string, brand string) interface{} {
	tx, err := lib.GetGormPool("default")
	if err != nil {
		panic(err)
	}
	uni, err := (&dao.Users{}).Find(c, tx, data.Unionid, "unionid")
	var self_id uuid.UUID = uuid.New()
	selfId := self_id.String()
	phone := ""
	if err != nil {
		data := &dao.Users{
			Openid:    data.OpenId,
			Unionid:   data.Unionid,
			Name:      data.NickName,
			Avatar:    data.AvatarUrl,
			Gender:    data.Gender,
			SelfId:    selfId,
			Fromwhere: from, Platform: platform, Brand: brand, UpdatedIp: remoteIp,
		}
		res, err2 := (&dao.Users{}).Add(c, tx, data)
		if err2 == nil {
			logadd := lib.GetStringConf("base.base.logadd")
			data2 := &dao.UsersHis{
				Type:     "add",
				Point:    logadd,
				Explains: "注册奖励",
				SelfId:   selfId,
			}
			his, _ := (&dao.UsersHis{}).AddData(c, tx, data2)
			fmt.Println(his)
		}
		fmt.Println(res.Id)
	} else {
		phone = uni.Phone
		selfId = uni.SelfId
		Users, err2 := (&dao.Users{}).Update(c, tx, selfId, remoteIp)
		if err2 != nil {
			return err2
		}
		fmt.Println(Users)
	}

	token := getToken(selfId)
	if token == "" {
		return errors.New("token生成失败")
	}
	return &DetailRes{
		Token:        token,
		RefreshToken: token,
		Phone:        phone,
	}
}

func getToken(uid string) string {
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
		"uid": uid,
	})
	hmacSampleSecret := lib.GetStringConf("base.base.hmacSampleSecret")
	tokenString, err := token.SignedString([]byte(hmacSampleSecret))
	if err != nil {
		fmt.Println("tokenerr", err)
		return ""
	}
	return tokenString
}

func ParseToken(tokenString string) interface{} {
	token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
		if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
			return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
		}
		hmacSampleSecret := lib.GetStringConf("base.base.hmacSampleSecret")
		return []byte(hmacSampleSecret), nil
	})
	if err != nil {
		return ""
	}
	if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
		return claims["uid"]
	} else {
		return ""
	}
}

func HttpGet(url string) string {
	res, err := http.Get(url)
	if err != nil {
		panic(err)
	}
	defer res.Body.Close()
	body, err := ioutil.ReadAll(res.Body)
	if err != nil {
		panic(err)
	}
	return string(body)
}
